<template>
  <view :data-theme="globPrimary">
    <u-navbar title="购物车">
      <view v-if="cartList.length > 0" slot="right" class="navbar-btn" @click="clickOperationBtn">
        {{ showOperation ? '完成' : '管理' }}
      </view>
    </u-navbar>
    <view class="cart-wrapper">
      <edu-mescroll-body
        @init="mescrollInit"
        height="calc(100vh - 44px - 98rpx)"
        @down="refresh"
        :up="upOption"
        @up="reachBottom"
      >
        <view class="mhm-wrap" v-for="cart in cartList" :key="cart.mhm_id">
          <view class="u-flex order-head u-border-bottom">
            <view class="u-flex">
              <u-checkbox
                :value="cart.checked"
                shape="circle"
                size="40"
                :active-color="globPrimaryColor"
                @change="onSelectAllChange($event, cart)"
              >
              </u-checkbox>
              <view class="name u-line-1">{{ cart.school_name }}</view>
            </view>
            <view class="btn" @click="openCouponPopup(cart.mhm_id)">领券</view>
          </view>
          <view class="u-flex order-wrap" v-for="(item, index) in cart.course_list" :key="index">
            <u-checkbox
              class="check_b"
              :value="item.checked"
              shape="circle"
              size="40"
              :active-color="globPrimaryColor"
              @change="onChildCheckChange($event, item)"
            ></u-checkbox>
            <EduCourseImage
              width="260"
              height="144"
              :border-radius="16"
              :image="item.cover_url"
              :courseType="item.course_type"
              :courseTypeText="item.course_type_text"
            ></EduCourseImage>
            <view class="content">
              <view class="title u-line-2">
                <u-image
                  v-if="item.has_course_card === 1"
                  width="72"
                  height="28"
                  src="@/pageCourse/static/images/lessoncard_icon.png"
                ></u-image>
                {{ item.title }}
              </view>
              <view class="u-flex">
                <view class="price">
                  <block v-if="userInfo.is_vip == 1">vip:</block>
                  {{ item.user_price | formatCurrency }}
                </view>
              </view>
            </view>
          </view>
        </view>

        <!-- 空数据 -->
        <edu-empty
          v-if="!loading && $u.test.empty(cartList)"
          :width="300"
          :height="264"
          description="还未加入课程哦~"
          image="/pageCourse/static/images/shoppingcart_placehoder_img.png"
        ></edu-empty>

        <view v-if="courseList.length > 0" class="cart-course">
          <view class="cart-course-header">
            <view class="line"></view>
            <u-image
              width="34"
              height="34"
              src="@/pageCourse/static/images/shoppingcart_heart_icon.png"
            ></u-image>
            <text class="text">精品推荐</text>
            <view class="line"></view>
          </view>
          <view class="cart-course-list">
            <view class="item" v-for="(item, index) in courseList" :key="index">
              <view class="picture">
                <EduCourseImage
                  :image="item.cover_url"
                  :border-radius="16"
                  width="100%"
                  height="100%"
                  :courseType="item.course_type"
                  :courseTypeText="item.course_type_text"
                  @click="goCourse(item.id)"
                >
                  <!-- 直播时间 -->
                  <view v-if="item.course_type == 2 && item.start_time > 0" class="time">
                    {{ item.start_time | date('mm月dd日 hh:MM') }}
                  </view>
                </EduCourseImage>
              </view>
              <view class="content">
                <view class="title" @click="goCourse(item.id)">{{ item.title }}</view>
                <view class="parallel">
                  <view class="num">{{ item.sale_count }}人报名</view>
                  <view class="free" v-if="item.is_buy">已购买</view>
                  <template v-else>
                    <view v-if="item.scribing_price > 0" class="s-price">{{
                      item.scribing_price | formatCurrency
                    }}</view>
                    <view class="price" v-if="item.user_price > 0">
                      {{ item.user_price | formatCurrency }}
                    </view>
                    <view v-else class="free">免费</view>
                  </template>
                </view>
              </view>
            </view>
          </view>
        </view>
      </edu-mescroll-body>
    </view>

    <view v-if="cartList.length > 0" class="bottom-placeholder">
      <view class="u-flex bottom-nav">
        <u-checkbox
          v-model="checkAll"
          shape="circle"
          size="40"
          :active-color="globPrimaryColor"
          @change="checkedAll"
          >全选</u-checkbox
        >
        <view class="total">
          合计：
          <text class="num">￥{{ totalPrice }}</text>
        </view>
        <view class="btn" @click="settlement">去结算</view>
      </view>

      <view class="bottom-operation" v-if="showOperation">
        <u-checkbox
          v-model="checkAll"
          shape="circle"
          size="40"
          :active-color="globPrimaryColor"
          @change="checkedAll"
          >全选</u-checkbox
        >
        <view @click="deletePayment" class="del-btn" :style="{ color: globPrimaryColor }">
          删除({{ checkLength }})</view
        >
      </view>
    </view>

    <!-- 机构的卡卷 -->
    <u-popup
      v-model="couponPopup"
      mode="bottom"
      border-radius="14"
      height="70%"
      @close="closeCouponPopup"
      class="coupon-wrapper"
    >
      <view class="coupon-title">卡券</view>
      <view class="coupon-list">
        <view class="item" v-for="(listItem, listIndex) in couponList" :key="listIndex">
          <view class="title">{{ listItem.coupon_type_text }}</view>
          <view
            class="ticket u-flex"
            :class="couponBgColorClass[item.coupon_type]"
            v-for="(item, index) in listItem.list"
            :key="item.id"
          >
            <block v-if="item.user_use == 0">
              <view class="left">
                <view class="top" v-if="item.coupon_type == 1">
                  <text class="big">
                    {{ item.price | formatCurrency }}
                  </text>
                  满{{ parseFloat(item.maxprice) }}减{{ parseFloat(item.price) }}
                </view>
                <view class="top" v-else-if="item.coupon_type == 2">
                  <text class="big">{{ parseFloat(item.discount) }}折</text>
                </view>
                <view class="top" v-else-if="item.coupon_type == 3"
                  ><text class="big">课程卡</text></view
                >
                <view class="type u-line-1" v-if="item.coupon_type == 3"
                  >仅限{{ item.course_title }}使用
                </view>
                <view class="type u-line-1" v-else>仅限{{ item.school_name }}使用</view>
                <view v-if="item.use_etime" class="date u-line-1">
                  有效期{{ item.use_stime | timeFormat('yyyy.mm.dd') }}至{{
                    item.use_etime | timeFormat('yyyy.mm.dd')
                  }}
                </view>
                <view v-else class="date u-line-1">永久有效</view>
              </view>
              <view class="u-flex u-row-center right">
                <view class="use active" :round="true" v-if="item.user_has == 1">已领取</view>
                <view
                  class="use"
                  :round="true"
                  v-else
                  @click="deriveCoupon(item.id, listIndex, index)"
                >
                  领取
                </view>
              </view>
            </block>
          </view>
        </view>
        <view class="u-flex u-row-center u-margin-top-20" v-if="couponLoading">
          <u-loading mode="flower" :show="couponLoading"></u-loading>
        </view>
        <edu-empty v-if="couponEmpty"></edu-empty>
      </view>
      <view class="coupon-bottom" v-if="!couponLoading">
        <view
          class="coupon-btn"
          :style="{ background: globPrimaryColor }"
          @click="couponPopup = false"
          >确定
        </view>
      </view>
    </u-popup>

    <u-modal
      show-cancel-button
      v-model="deleteModal"
      :show-title="false"
      @confirm="handlePaymentDelete"
      cancel-text="再想想"
      confirm-text="删除"
      :confirm-style="{ 'border-left': '1px solid #e4e7ed' }"
      confirm-color="#f54030"
    >
      <view class="model-wrapper">确认删除吗?</view>
    </u-modal>

    <u-modal
      show-cancel-button
      v-model="showCourseCard"
      :show-title="false"
      :confirm-style="{ 'border-left': '1px solid #e4e7ed' }"
      confirm-text="去取消"
      cancel-text="继续付款"
      :confirm-color="globPrimaryColor"
      @cancel="jump"
    >
      <view class="model-wrapper">
        订单含有课程卡课程
        <br />
        是否取消勾选？
      </view>
    </u-modal>
  </view>
</template>

<script>
import EduCourseImage from '@/components/common/courseImage.vue'
import { mapGetters } from 'vuex'
export default {
  components: {
    EduCourseImage,
  },
  data() {
    return {
      typeClass: {
        1: 'video',
        2: 'live',
        3: 'multipart',
        4: 'classes',
      },
      cartList: [],
      couponList: [],
      couponPopup: false,
      couponLoading: false,
      couponEmpty: false,
      checkAll: false,
      showOperation: false,
      deleteModal: false,
      couponBgColorClass: {
        1: 'youhui',
        2: 'dazhe',
        3: 'kechengka',
      },
      showCourseCard: false,
      upOption: {
        isLock: true,
        empty: {
          use: false,
        },
      },
      courseList: [],
      loading: true,
    }
  },
  computed: {
    ...mapGetters({
      globPrimary: 'designSetting/getGlobTheme',
      globPrimaryColor: 'designSetting/getGlobThemeColor',
      userInfo: 'user/getUserInfo',
    }),
    // 总价
    totalPrice() {
      let total = 0
      this.cartList.forEach((subItem) => {
        subItem.course_list.forEach((item) => {
          if (item.checked) {
            total += item.user_price
          }
        })
      })
      return total != 0 ? total.toString().replace(/\B(?=(\d{3})+$)/g, ',') : 0
    },
    // 获取选中商品的数量
    checkLength() {
      let total = 0
      this.cartList.forEach((subItem) => {
        let data = subItem.course_list.filter((item) => item.checked === true)
        total += data.length
      })
      return total
    },
    // 获取选中商品的id
    checkedPaymentList() {
      let total = []
      this.cartList.forEach((item) => {
        item.course_list.forEach((subItem) => {
          if (subItem.checked) {
            total.push(subItem.id)
          }
        })
      })
      return total.toString()
    },
  },
  watch: {
    cartList: {
      deep: true, // 表示深度监听数据
      handler(newVal, val) {
        // 1. 遍历数据 找出被选中的店铺
        this.cartList.forEach((item) => {
          let checked =
            item.course_list.filter((sub_item) => sub_item.checked).length ==
            item.course_list.length
          // 3. 如果两者相等则将店铺的选中状态变为true
          if (checked) {
            item.checked = checked
          } else {
            // 4. 否则 false
            item.checked = false
          }
        })

        // ------------------- 底部全选框的全选反选 ---------------------
        // 1. 过滤出来已选中的店铺
        let dp_checked = this.cartList.filter((item) => item.checked)
        // 2. 判断已选中的店铺长度是否等于购物车店铺的长度
        if (this.cartList.length > 0 && dp_checked.length === this.cartList.length) {
          // 3. 如果两者相等则将全选状态变为 true , 否则为false
          this.checkAll = true
        } else {
          this.checkAll = false
        }
      },
    },
  },
  options: {
    styleIsolation: 'shared',
  },
  mounted() {
    this.getCourseSplendid()
  },
  onShow() {
    this.refresh()
  },
  methods: {
    // 下拉刷新
    refresh() {
      this.mescroll && this.mescroll.resetUpScroll()
    },
    reachBottom() {
      // 获取订单信息
      this.$edu.api.getPaymentCart().then((res) => {
        const { data } = res
        data.forEach((school, school_index) => {
          school.checked = false
          school.course_list.forEach((item, index) => {
            item.checked = false
          })
        })
        this.cartList = data
        this.mescroll.endSuccess(data.length, false)
        this.loading = false
      })
    },
    // 推荐课程
    getCourseSplendid() {
      this.$edu.api
        .getCourseList({
          order: 'splendid',
          page: 1,
          count: 10,
        })
        .then((res) => {
          const { data } = res
          this.courseList = data.data
        })
    },
    // 机构全选
    onSelectAllChange(event, item) {
      item.course_list.forEach((subItem) => {
        subItem.checked = event.value
      })
    },
    // 产品选中
    onChildCheckChange(event, item) {
      item.checked = event.value
    },
    // 结算时全选
    checkedAll(e) {
      this.cartList.forEach((item) => {
        item.course_list.forEach((subItem) => {
          subItem.checked = e.value
        })
      })
    },
    // 点击管理按钮
    clickOperationBtn() {
      this.showOperation = !this.showOperation
    },
    // 删除前处理
    deletePayment() {
      if (this.$u.test.empty(this.checkedPaymentList)) {
        this.$u.toast('您还没有选择商品哦')
      } else {
        this.deleteModal = true
      }
    },
    // 删除商品
    handlePaymentDelete() {
      this.$edu.api
        .deletePaymentCart({
          course_ids: this.checkedPaymentList,
        })
        .then((res) => {
          this.$u.toast(res.msg)
          // 更新购物车数量
          this.$store.dispatch('projectSetting/setGlobCartNumber')
          this.mescroll.resetUpScroll(false)
        })
        .catch((res) => {
          this.$u.toast(res.msg)
        })
    },
    // 打开卡卷
    openCouponPopup(id) {
      this.couponPopup = true
      this.getCouponData(id)
    },
    // 关闭卡卷弹窗
    closeCouponPopup() {
      this.couponList = []
    },
    // 获取机构卡卷的数据
    getCouponData(id) {
      this.couponLoading = true
      this.couponEmpty = false
      this.$edu.api
        .getCourseCouponSchool({
          mhm_id: id,
          group: 1,
        })
        .then((res) => {
          let data = res.data
          data = data.filter((item) => {
            // 过滤空
            return !this.$u.test.empty(item.list)
          })
          if (this.$u.test.empty(data)) this.couponEmpty = true
          this.couponList = data
          this.couponLoading = false
        })
        .catch((res) => {
          this.couponLoading = false
        })
    },
    // 领取卡卷
    deriveCoupon(id, l, i) {
      this.$edu.api
        .postCourseCouponDerive(id)
        .then((res) => {
          this.$u.toast(res.msg)
          this.couponList[l].list[i].user_has = 1
          this.couponList = Object.assign([], this.couponList)
        })
        .catch((res) => {
          this.$u.toast(res.msg)
        })
    },
    // 结算
    settlement() {
      if (this.checkLength == 0) {
        this.$u.toast('请选择要购买的课程')
        return
      }
      var typeArr = []
      // 提交的订单是否有课程卡
      this.cartList.forEach((it) => {
        var showType = it.course_list.some((item) => item.checked && item.has_course_card == 1)
        typeArr.push(showType)
      })
      if (typeArr.includes(true)) {
        this.showCourseCard = true
      } else {
        this.jump()
      }
    },
    // 支付
    jump() {
      this.$u.route('/pageCourse/cart/order', {
        id: this.checkedPaymentList,
      })
    },
    // 跳转课程
    goCourse(id) {
      this.$u.route('/pageCourse/course/details', {
        id: id,
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.navbar-btn {
  font-size: 30rpx;
  font-weight: 400;
  color: $edu-main-color;
  margin-right: 30rpx;
}

.mhm-wrap {
  background-color: #fff;
  padding-bottom: 35rpx;
  margin-top: 20rpx;

  /deep/.u-checkbox__label {
    display: none;
  }

  .order-head {
    height: 98rpx;
    margin-bottom: 32rpx;
    padding: 0 30rpx;
    .name {
      font-size: 30rpx;
      font-weight: 500;
      color: $edu-main-color;
      margin-left: 24rpx;
      max-width: 520rpx;
    }

    .btn {
      font-size: 26rpx;
      font-weight: 400;
      color: $edu-main-color;
      margin-left: auto;
    }
  }

  .order-wrap + .order-wrap {
    margin-top: 24rpx;
  }

  .order-wrap {
    /* #ifdef MP-WEIXIN */
    display: flex;
    /* #endif */
    padding: 0 30rpx;

    /* #ifdef MP-WEIXIN */
    .check_b {
      margin-right: 24rpx;
    }
    /* #endif */
    .u-checkbox {
      margin-right: 24rpx;
    }

    .content {
      flex: 1;
      margin-left: 16rpx;

      .title {
        height: 72rpx;
        font-size: 28rpx;
        font-weight: 400;
        color: $edu-main-color;
        line-height: 36rpx;
        margin-bottom: 38rpx;
        .u-image {
          display: inline-block;
          margin-right: 4rpx;
          vertical-align: middle;
        }
      }

      .price {
        font-size: 24rpx;
        font-weight: 500;
        color: $edu-price-color;
      }
    }
  }
}

.cart-wrapper {
  ::v-deep.edu-empty {
    background-color: #ffffff;
  }
}

.coupon-wrapper {
  ::v-deep .uni-scroll-view {
    position: static;
  }
  .coupon-title {
    font-size: 32rpx;
    font-weight: 500;
    color: $edu-main-color;
    height: 100rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .coupon-list {
    padding: 0 30rpx;
    min-height: calc(100% - 212rpx);
    .item {
      & + .item {
        margin-top: 45rpx;
      }

      .title {
        font-size: 28rpx;
        font-weight: 400;
        color: $edu-tips-color;
      }
    }

    .ticket {
      width: 100%;
      margin-top: 32rpx;
      background-image: var(--bg-img);
      background-size: 100% 100%;
      background-repeat: no-repeat;

      .left {
        width: 70%;
        padding: 20rpx 25rpx;
        color: var(--main-color);

        .top {
          font-size: 28rpx;

          .big {
            font-size: 40rpx;
            font-weight: 400;
            margin-right: 10rpx;
          }
        }

        .type {
          font-size: 24rpx;
          margin-top: 18rpx;
        }

        .date {
          margin-top: 6rpx;
          font-size: 24rpx;
        }
      }

      .right {
        width: 30%;
        .use {
          width: 150rpx;
          height: 68rpx;
          border-radius: 34rpx;
          border-width: 2rpx;
          border-style: solid;
          color: #ffff;
          font-size: 30rpx;
          line-height: 64rpx;
          text-align: center;
          border-color: var(--main-color);
          background-color: var(--main-color);

          &.active {
            color: var(--main-color);
            border-color: transparent;
            background-color: transparent;
          }
        }
      }

      &.youhui {
        --main-color: #ff8a52;
        --bg-img: url('@/pageCourse/static/images/youhuiquan.png');
      }

      &.dazhe {
        --main-color: #ff9431;
        --bg-img: url('@/pageCourse/static/images/dazhe_bg.png');
      }

      &.kechengka {
        --main-color: #67c23a;
        --bg-img: url('@/pageCourse/static/images/kechengka.png');
      }
    }
  }

  .coupon-bottom {
    padding: 10rpx 55rpx;
  }

  .coupon-btn {
    height: 72rpx;
    border-radius: 36px;
    font-size: 32rpx;
    font-weight: 400;

    color: #ffffff;
    display: flex;
    align-items: center;
    justify-content: center;
    @include bg-color();
  }
}

.bottom-placeholder {
  height: 98rpx;
}

.bottom-nav {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9;
  height: 98rpx;
  padding: 0 30rpx;
  background: #ffffff;
  box-shadow: 0px 2rpx 14rpx 0px rgba(0, 0, 0, 0.06);

  /deep/.u-checkbox__label {
    color: $edu-tips-color;
  }

  .total {
    margin-left: auto;
    font-size: 26rpx;
    font-weight: 400;
    color: $edu-main-color;

    .num {
      font-size: 30rpx;
      font-weight: 500;
      color: $edu-price-color;
    }
  }

  .btn {
    width: 220rpx;
    height: 72rpx;
    @include bg-color();
    border-radius: 39rpx;
    font-size: 32rpx;
    font-weight: 400;
    color: #ffffff;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-left: 28rpx;
  }
}

.bottom-operation {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 10;
  height: 98rpx;
  padding: 0 30rpx;
  background: #ffffff;
  box-shadow: 0px 2rpx 14rpx 0px rgba(0, 0, 0, 0.06);
  font-size: 32rpx;
  font-weight: 400;
  display: flex;
  align-items: center;
  justify-content: space-between;

  /deep/.u-checkbox__label {
    color: $edu-tips-color;
  }

  .del-btn {
    @include text-color();
  }
}

.model-wrapper {
  height: 170rpx;
  font-size: 32rpx;
  font-weight: 400;
  color: $edu-main-color;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cart-wrapper {
  ::v-deep.cart-course {
    margin-top: 20rpx;
    padding: 60rpx 30rpx;
    background: #ffffff;
    .cart-course-header {
      display: flex;
      align-items: center;
      justify-content: center;
      .line {
        width: 122rpx;
        height: 1rpx;
        background: #dcdfe6;
        margin: 0 40rpx;
      }
      .text {
        margin-left: 12rpx;
        font-size: 32rpx;
        font-weight: 600;
        color: #303133;
      }
    }
    .cart-course-list {
      margin-top: 40rpx;
      display: grid;
      grid-gap: 28rpx 22rpx;
      grid-template-columns: repeat(2, minmax(0px, 1fr));
      padding: 22rpx 22rpx 32rpx;
      box-shadow: 0rpx 0rpx 40rpx 0rpx rgba(48, 49, 51, 0.06);
      border-radius: 16rpx;
      .item {
        grid-column: span 1 / span 1;
        .picture {
          width: 100%;
          height: 172rpx;
          .time {
            padding: 0 8rpx;
            height: 32rpx;
            font-size: 20rpx;
            color: #ffffff;
            line-height: 32rpx;
            background: rgba(48, 49, 51, 0.4);
            border-radius: 8rpx;
            position: absolute;
            bottom: 8rpx;
            left: 8rpx;
          }
          .img-promotion {
            position: absolute;
            right: 0;
            bottom: 0;
            width: 30px;
            height: 16px;
            &.big {
              width: 50px;
            }
          }
          .img-course {
            position: absolute;
            top: 0;
            left: 0;
            width: 28px;
            height: 16px;
          }
        }
        .content {
          margin-top: 16rpx;
          .title {
            font-size: 28rpx;
            color: #333333;
            font-weight: 500;
            line-height: 40rpx;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
          }
          .parallel {
            display: flex;
            align-items: center;
            margin-top: 18rpx;
            .num {
              flex: 1;
              min-width: 0;
              font-size: 22rpx;
              font-weight: 400;
              color: $edu-tips-color;
            }
            .save {
              margin-left: 10rpx;
              padding: 6rpx 8rpx;
              font-size: 20rpx;
              font-weight: 400;
              color: $edu-price-color;
              line-height: 30rpx;
              background: #fff5f4;
              border-radius: 8rpx;
              position: relative;
              .triangle {
                position: absolute;
                top: 50%;
                margin-top: -2rpx;
                left: -5rpx;
              }
            }
            .s-price {
              font-size: 22rpx;
              font-weight: 400;
              color: #888888;
              line-height: 26rpx;
              text-decoration: line-through;
              margin-right: 5px;
            }
            .price {
              font-size: 32rpx;
              font-weight: 500;
              color: $edu-price-color;
              &.font12 {
                font-size: 24rpx;
              }
            }
            .free {
              font-size: 30rpx;
              font-weight: 500;
              color: $edu-free-color;
            }
            .btn {
              width: 148rpx;
              height: 52rpx;
              font-size: 26rpx;
              font-weight: 400;
              color: #ffffff;
              line-height: 52rpx;
              text-align: center;
              border-radius: 28rpx;
              @include bg-color();
            }
          }
        }
      }
    }
  }
}
</style>
